import { Component, OnInit } from '@angular/core';
import { MenuService } from './menu.service';
import { Menu } from './domain/menu';
import { Response } from '../../../core/domain/response';
import { NzMessageService } from 'ng-zorro-antd';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { StatusEnum } from '../../../core/enum/status.enum';

@Component({
  selector: 'app-menu',
  templateUrl: './menu.component.html',
  styleUrls: ['./menu.component.scss'],
  providers: [MenuService]
})
export class MenuComponent implements OnInit {
  isEdit = true;
  // 页面菜单树
  tree: TreeNodeInterface[] = [];
  // 单条菜单信息
  menu: Menu = new Menu();
  // 联级选择数据
  cascader: Cascader[] = [];
  mapOfExpandedData: { [key: string]: TreeNodeInterface[] } = {};
  // 是否打开新增编辑菜单
  isAddEdit = false;

  // 表单对象
  validateForm: FormGroup;

  constructor(private pageServe: MenuService,
              private message: NzMessageService,
              private formBuilder: FormBuilder) {
  }

  ngOnInit() {
    // 进入页面立即获取菜单树
    this.pageTree();
    // 获取父级下拉树
    this.listTree();
    // 初始化表单对象
    this.initForm();
  }

  /**
   * 转换树列表
   */
  convertTreeToList(root: object): TreeNodeInterface[] {
    const stack: any[] = [];
    const array: any[] = [];
    const hashMap = {};
    stack.push({...root, level: 0, expand: false});
    while (stack.length !== 0) {
      const node = stack.pop();
      this.visitNode(node, hashMap, array);
      if (node.children) {
        for (let i = node.children.length - 1 ; i >= 0 ; i--) {
          stack.push({...node.children[i], level: node.level + 1, expand: false, parent: node});
        }
      }
    }
    return array;
  }

  /**
   * 可视节点
   */
  visitNode(node: TreeNodeInterface, hashMap: { [key: string]: any }, array: TreeNodeInterface[]): void {
    if (!hashMap[node.key]) {
      hashMap[node.key] = true;
      array.push(node);
    }
  }

  initForm() {
    this.validateForm = this.formBuilder.group({
      icon: [null, []],
      name: [null, [Validators.required]],
      parentId: [null, [Validators.required]],
      remark: [null, []],
      showLevel: [null, [Validators.required]],
      status: [null, []],
      targetType: [],
      type: [null, [Validators.required]],
      url: [null, []]
    });
  }

  /**
   * 获取菜单信息
   */
  pageTree(): void {
    this.pageServe.pageQuery().subscribe((res: Response) => {
      const {datas, status} = res;
      if (status === StatusEnum.SUCCESS) {
        // 菜单树
        this.tree = datas;
        this.tree.forEach(item => {
          this.mapOfExpandedData[item.key] = this.convertTreeToList(item);
        });
        this.listTree();
      }
    });
  }

  /**
   * 查询级联选择树
   */
  listTree() {
    this.pageServe.listTree().subscribe(res => {
      const {datas, status} = res;
      if (status === StatusEnum.SUCCESS) {
        this.cascader = [{
          title: '根节点',
          key: '980989898999',
          children: datas
        }];
      }
    });
  }

  /**
   * 直接新增菜单
   */
  addBtn() {
    this.isEdit = false;
    // 初始化表单对象
    this.initForm();
    // 初始化编辑节点
    this.menu = new Menu();
    // 打开新增编框
    this.isAddEdit = true;
  }

  /**
   * 添加子菜单信息
   * @param menuId 菜单Id
   */
  addMenuOwn(menuId: string) {
    this.isEdit = false;
    // 初始化表单对象
    this.initForm();
    this.menu = new Menu();
    this.menu.parentId = menuId;
    this.isAddEdit = true;
  }

  /**
   * 编辑单条菜单信息
   * @param menuId 菜单Id
   * @param isEdit 查看
   */
  editMenu(menuId: string, isEdit) {
    this.isEdit = isEdit;
    this.pageServe.editSee(menuId).subscribe((res: Response) => {
      const {status, datas, message} = res;
      if (status === StatusEnum.SUCCESS) {
        this.menu.parentId = menuId;
        this.menu = datas;
        this.isAddEdit = true;
      }
    });
  }

  /**
   * 删除菜单
   * @param menuId 菜单Id
   */
  deleteMenu(menuId: string): void {
    this.pageServe.delete(menuId).subscribe((res: Response) => {
      const {status, message} = res;
      if (status === StatusEnum.SUCCESS) {
        this.message.success(message);
        this.pageTree();
      }
    });
  }

  /**
   * 新增编辑菜单数据提交
   */
  submit() {
    let submitType = 'create';
    if (this.menu.id) {
      submitType = 'update';
    }
    this.pageServe[submitType](this.menu).subscribe((res: Response) => {
      const {status, message} = res;
      if (status === StatusEnum.SUCCESS) {
        this.message.success(message);
        this.isAddEdit = false;
        this.pageTree();
      }
    });
  }

  /**
   * 展开节点
   */
  collapse(array: TreeNodeInterface[], data: TreeNodeInterface, $event: boolean): void {
    if ($event === false) {
      if (data.children) {
        data.children.forEach(d => {
          const target = array.find(a => a.key === d.key)!;
          target.expand = false;
          this.collapse(array, target, false);
        });
      } else {
        return;
      }
    }
  }
}

export class Cascader {
  children?: Cascader[];
  disabled?: boolean;
  parentId?: string;
  isLeaf?: boolean;
  key?: string;
  title?: string;
  value?: string;
}

/**
 * 部门树
 */
export interface TreeNodeInterface {
  isLeaf: boolean;
  key?: string;
  leader?: string;
  title?: string;
  value?: string;
  expand: boolean;
  url?: string;
  children?: TreeNodeInterface[];
}
